import React, { Component } from 'react'
import store from '../../redux/store'
import { createIncrementAction, createDecrementAction } from '../../redux/count_action_creator'

export default class Count extends Component {

    componentDidMount() {
        //检测redux中状态的变化，只要变化就调用 render方法
        // 也可以在index.js入口文件中配置，这样可以一劳永逸不必再在各组件中写此监听语句
        // store.subscribe(() => {
        //     this.setState({})
        // })
    }

    increment = () => {
        const { value } = this.selectNum
        store.dispatch(createIncrementAction(value * 1))
    }
    decrement = () => {
        const { value } = this.selectNum
        store.dispatch(createDecrementAction(value * 1))
    }
    incrementIfOdd = () => {
        const { value } = this.selectNum
        const sum = store.getState()
        if (sum % 2 !== 0) {
            store.dispatch(createIncrementAction(value * 1))
        }
    }
    aysncIncrement = () => {
        const { value } = this.selectNum
        setTimeout(() => {
            store.dispatch(createIncrementAction(value * 1))
        }, 1000)
    }

    render() {
        return (
            <div>
                <h2>求和得：{store.getState()}</h2>
                <div>
                    <select ref={c => this.selectNum = c}>
                        <option value={1}>1</option>
                        <option value={2}>2</option>
                        <option value={3}>3</option>
                    </select>&nbsp;

                    <button onClick={this.increment}>+</button>&nbsp;
                    <button onClick={this.decrement}>-</button>&nbsp;
                    <button onClick={this.incrementIfOdd}>奇数时加</button>&nbsp;
                    <button onClick={this.aysncIncrement}>异步加</button>
                </div>
            </div>
        )
    }
}
